package com.jrx.mservices.provide.controller;

import com.jrx.mservices.provide.model.ServiceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * 提供者接口类
 *
 * @author zwg
 * @create 2018-03-06 16:36
 */
@RestController
@RequestMapping("provide")
public class ProvideContrller {

    public static final Logger logger = LoggerFactory.getLogger(ProvideContrller.class);

    @Autowired
    private DiscoveryClient client;

    /**
     * 测试方法
     * @param waitTime  线程休眠时间 毫秒，默认为0，不休眠
     * @return
     */
    @RequestMapping(value = "test",method = RequestMethod.GET)
    public String test(@RequestParam(defaultValue = "0") long waitTime){
        List<String> services = client.getServices();

        if(waitTime>0){
            try {
                logger.info("begin wait "+waitTime+"....");
                Thread.sleep(waitTime);
                logger.info("end wait "+waitTime+"....");
            } catch (InterruptedException e) {
                logger.error("线程休眠错误：",e);
            }
        }

        StringBuilder res = new StringBuilder();
        res.append("this is provider func, ");
        res.append("services:").append(services!=null?services:"null");
        logger.info(res.toString());
        return res.toString();
    }

    /**
     * 测试方法
     * @param waitTime  线程休眠时间 毫秒，默认为0，不休眠
     * @return
     */
    @RequestMapping(value = "testObj",method = RequestMethod.GET)
    public List<ServiceInfo> testObj(@RequestParam(defaultValue = "0") long waitTime){
        List<String> services = client.getServices();

        if(waitTime>0){
            try {
                logger.info("begin wait "+waitTime+"....");
                Thread.sleep(waitTime);
                logger.info("end wait "+waitTime+"....");
            } catch (InterruptedException e) {
                logger.error("线程休眠错误：",e);
            }
        }

        List<ServiceInfo> resList = new ArrayList<>();
        if(services!=null && !services.isEmpty()){
            for (String serviceName : services) {
                List<ServiceInstance> siList = client.getInstances(serviceName);
                if(siList!=null && !siList.isEmpty()){
                    for (ServiceInstance si : siList) {
                        resList.add(new ServiceInfo(si.getServiceId(),si.getHost(),si.getPort(),si.isSecure(),si.getUri()));
                    }
                }
            }
        }
        return resList;
    }


}
